<template>
  <div class="userManage">
    <!--    <el-button @click="addUser" type="primary" icon="img icon-add" style="margin:0 0 20px;">新增本单位用户</el-button>-->
    <tablePage ref="tablePage" :searchForm.sync="searchForm" :requestFunc="requestFunc" labelWidth="110px">
      <template slot="search-form">
        <el-form-item label="部门" prop="orgCode">
          <el-cascader
            ref="cascader"
            style="width: 100%"
            v-model="searchForm.orgCode"
            :props="{ children: 'children', label: 'name', value: 'code', expandTrigger: 'hover', emitPath: false, checkStrictly: true }"
            :options="departmentTree"
            :show-all-levels="false"
            placeholder="请选择部门"
            @change="$refs.cascader && $refs.cascader.toggleDropDownVisible(false)"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input v-model="searchForm.name" placeholder="搜索用户"></el-input>
        </el-form-item>
      </template>

      <template slot="left">
        <el-button @click="addUser" type="primary" icon="img icon-add">新增本单位用户</el-button>
      </template>

      <template slot="rows">
        <el-table-column prop="accountName" label="登录名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="name" label="别名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="orgName" label="部门角色" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ row.roleNames }}
            <!--            部门成员{{ row.roles | roleNames(that) }}-->
          </template>
        </el-table-column>
        <el-table-column prop="telephone" label="电话" show-overflow-tooltip></el-table-column>
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" align="center" width="260">
          <template slot-scope="{ row }">
            <el-button type="primary" :disabled="loading" @click="editUserInfo(row)" plain size="mini">编辑</el-button>
            <el-button type="primary" @click="setStatusFun(row, 1)" plain size="mini" v-if="row.status == '0'">启用</el-button>
            <el-button type="primary" @click="setStatusFun(row, 0)" plain size="mini" v-if="row.status == '1'">禁用</el-button>
            <el-button type="primary" @click="resetPasswordFun(row)" plain size="mini">重置密码</el-button>
          </template>
        </el-table-column>
      </template>
    </tablePage>

    <setUserInfoDialog
      :visible="visible"
      :type="type"
      :currentAccountId="currentAccountId"
      :userForm="userForm"
      :userInfo="userInfo"
      :oldTelephone="oldTelephone"
      :oldEmail="oldEmail"
      :accountRoleTypeTypeDict="accountRoleTypeTypeDict"
      @handleClose="handleClose"
      @getNewList="getNewList"
    ></setUserInfoDialog>
  </div>
</template>

<script>
import tablePage from "@/components/tablePage/index.vue";
import * as userManageAPI from "@/api/userManage";

import setUserInfoDialog from "./components/setUserInfoDialog";
import { accountRoleTypeType, accountRoleTypeTypeByString, delTemporary } from "@/utils/filters";
import { accountRoleTypeTypeDict } from "@/utils/dict";
import { userDetail, setStatus, resetPassword, userDeptTree } from "@/api/userManage";
import * as departmentConfigureAPI from "@/api/departmentConfigure";
import { removeEmptyChildren } from "@/utils/common";

export default {
  name: "userManage",
  components: {
    tablePage,
    setUserInfoDialog,
  },
  filters: {
    accountRoleTypeTypeByString,
    delTemporary,
    // configureMapCustomName(val, that) {
    //   for (const item of that.configureMap) {
    //     if (item.id )
    //   }
    // }
    roleNames(ids, that) {
      ids = ids.split(",");
      const names = [];
      for (const id of ids) {
        if (accountRoleTypeType(id) !== "-") {
          names.push(accountRoleTypeType(id));
          continue;
        }
        for (const item of that.configureMap) {
          if (item.id === id && item.value === "1") {
            names.push(item.customName);
          }
        }
      }
      return "," + names.join(", ");
    },
  },
  data() {
    return {
      that: this,
      loading: false,
      searchForm: {
        name: "",
        orgCode: [],
      },
      visible: false,
      type: "add",
      userForm: {
        accountId: "",
        loginName: "",
        region: [],
        roles: [],
        name: "",
        telephone: "",
        email: "",
        file: "",
        orgName: "",
        systemName: "",
        systemId: "",
        accountSystem: "",
      },
      oldEmail: "",
      oldTelephone: "",
      userInfo: null,
      configureMap: [],
      accountRoleTypeTypeDict,
      departmentTree: [],
      currentAccountId: "",
    };
  },
  computed: {},

  created() {
    departmentConfigureAPI.getTypeList().then((r) => {
      const result = r.result;
      this.configureMap = result;
      // 添加 accountRoleTypeTypeDict
      for (const item of result) {
        if (item.value === "1") {
          this.accountRoleTypeTypeDict[String(item.id)] = item.customName;
        }
      }
      console.log(">>", this.accountRoleTypeTypeDict);
    });
    this.fetchDepartmentTree();
  },
  methods: {
    requestFunc: userManageAPI.list,
    fetchDepartmentTree() {
      userDeptTree().then((res) => {
        const result = res.result;
        if (result) {
          removeEmptyChildren([result]);
          this.departmentTree = [result];
          this.searchForm.orgCode = [result.code];
          this.$refs.tablePage.handleSearch();
        }
      });
    },

    //新增用户
    addUser() {
      this.userForm.accountId = "";
      this.userForm.loginName = "";
      this.userForm.region = [];
      this.userForm.roles = ["0"];
      this.userForm.name = "";
      this.userForm.telephone = "";
      this.userForm.email = "";
      this.userForm.file = "";
      this.userForm.orgName = "";
      this.userForm.systemName = "";
      this.userForm.systemId = "";
      this.userForm.accountSystem = "";
      this.type = "add";
      this.visible = true;
      // console.log(this.$refs.tablePage);
    },
    //编辑用户
    editUserInfo(row) {
      let params = {
        userAccountId: row.accountId,
      };
      this.currentAccountId = row.accountId;
      this.loading = true;
      userDetail(params)
        .then((res) => {
          const { code, msg, result } = res;
          if (code === 0) {
            this.userInfo = result;
            this.userForm.accountId = result.id;
            this.userForm.loginName = result.accountName;
            this.userForm.roles = result.complainRoles ? result.complainRoles.split(",") : [];
            // for(let i=0;i<this.userForm.roles.length;i++){
            //   if(!this.accountRoleTypeTypeDict.hasOwnProperty(String(this.userForm.roles[i]))){
            //     this.userForm.roles.splice(i,1)
            //     i--
            //   }
            // }
            // debugger
            // console.log(this.userForm.roles, accountRoleTypeTypeDict)
            !this.userForm.roles.find((k) => k === "0") && this.userForm.roles.unshift("0");
            this.userForm.name = result.name;
            this.userForm.telephone = result.telephone;
            this.userForm.email = result.email;
            this.oldEmail = result.email;
            this.oldTelephone = parseInt(result.telephone);
            this.userForm.file = result.imgURL;
            this.userForm.orgName = result.orgName;
            this.userForm.systemName = result.systemName;
            this.userForm.systemId = result.systemId;
            this.userForm.accountSystem = result.accountSystem;
            let region = [];
            if (this.userInfo.orgId) {
              // region.push(this.userInfo.orgId.split(','))
              region = this.userInfo.orgId.split(",");
              region.reverse();
            }
            this.userForm.region = region;
            // console.log(this.userForm.region);
            this.type = "edit";
            this.visible = true;
          }
        })
        .finally(() => (this.loading = false));
    },
    //刷新当前页面列表
    getNewList() {
      this.handleClose();
      if (this.type === "add") {
        this.$refs.tablePage.pageQuery.pageNum = 1;
      }
      this.$refs.tablePage.playLoadData();
    },
    handleClose() {
      this.userForm = {};
      this.visible = false;
    },
    //修改用户状态
    setStatusFun(row, type) {
      const vm = this;
      const confirm = [`确认禁用${row.name}？`, "确定启用该用户？"];
      this.$confirm(confirm[type], "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            accountId: row.accountId,
            status: type,
          };
          setStatus(params)
            .then((res) => {
              const { code, msg } = res;
              if (code == 0) {
                this.$message.success(msg);
                this.$refs.tablePage.playLoadData();
              } else {
                this.$message.error(msg);
              }
            })
            .catch((err) => {
              return Promise.reject(err);
            });
        })
        .catch((err) => {
          return Promise.reject(err);
        });
    },
    //重置密码resetPassword
    resetPasswordFun(row) {
      this.$confirm(`确认重置${row.name}的密码？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            accountId: row.accountId,
            accountName: row.accountName,
            email: row.email,
            name: row.name,
          };
          resetPassword(data)
            .then((res) => {
              const { code, msg } = res;
              if (code === 0) {
                this.$message.success("密码重置成功");
                this.$refs.tablePage.playLoadData();
              } else {
                this.$message.error(msg);
              }
            })
            .catch((err) => {
              return Promise.reject(err);
            });
        })
        .catch((err) => {
          return Promise.reject(err);
        });
    },
  },
};
</script>

<style scoped lang="less"></style>
